﻿using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using log4net;

namespace ZK.Common
{
    public class LogHelper
    {
        public static string CurrentlogState
        {
            get
            {
                string state = Settings.GetAppConfig("LogSwitch");
                return TemporaryVar.logState = string.IsNullOrWhiteSpace(state) ? "0" : state == "off" ? "0" : state;
            }
        }

        /// <summary>
        /// 存储当前状态  不用每次读取config
        /// </summary>
        public static bool IsLogSwitch
        {
            get { return (TemporaryVar.logState == "off" ? CurrentlogState : TemporaryVar.logState) == "0" ? true : false; }
        }

        public static void LogInfo(string info)
        {
            if (IsLogSwitch) return;
            LogManager.GetLogger(GetTypeFromStackTrace()).Info(info);
        }

        public static void LogWarn(string warn)
        {
            LogManager.GetLogger(GetTypeFromStackTrace()).Warn(warn);
        }

        public static void LogDebug(string debug)
        {
            if (IsLogSwitch) return;
            LogManager.GetLogger(GetTypeFromStackTrace()).Debug(debug);
        }

        public static void LogError(string error, Exception ex = null)
        {
            LogManager.GetLogger(GetTypeFromStackTrace()).Error(error, ex);
        }

        public static void LogFatal(string fatal, Exception ex = null)
        {
            if (IsLogSwitch) return;
            LogManager.GetLogger(GetTypeFromStackTrace()).Fatal(fatal, ex);
        }

        //public static  Task<string> ReadLog()
        //{
        //    var reader = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log/TaskSchedule.log"));
        //    return  reader.ReadToEnd();
        //}

        private static Type GetTypeFromStackTrace()
        {
            var st = new StackTrace();
            var sf = st.GetFrame(2);
            return sf?.GetMethod()?.DeclaringType;
        }
    }
}